#include "AdWnd.h"
#include <QPixmap>
#include <QPainter>
#include <QTimer>
#include <QFile>
#include <QLabel>

CAdWnd::CAdWnd(QWidget* parent)
	: QWidget(parent)
	, index_(0)
	, timer_(new QTimer(this))
{
	timer_->stop();
	connect(timer_, &QTimer::timeout, this, [&]() {
		QMutexLocker locker(&mutex_);
		index_ += 1;
		if (index_ >= list_.size())
		{
			index_ = 0;
		}
        this->update();
	});
}

CAdWnd::~CAdWnd()
{
	timer_->stop();
}

void CAdWnd::SetInterval(int32_t itl)
{
	timer_->stop();
	timer_->setInterval(itl);
	timer_->start();
}

void CAdWnd::SetVersion(const QString & version)
{
	version_ = QString(tr("Current Version:%1").arg(version));
}

void CAdWnd::SetFileList(QVector<QString> list)
{
	QMutexLocker locker(&mutex_);
	list_.clear();
	foreach(const QString& p, list)
	{
		auto pix = load_pixmap_from_file(p);
		if (!pix.isNull())
		{
			list_.push_back(pix);
		}
	}
}

void CAdWnd::ClearList()
{
	QMutexLocker locker(&mutex_);
	list_.clear();
}

void CAdWnd::AppendFile(QString filename)
{
	QMutexLocker locker(&mutex_);
	QPixmap pix;
	if (pix.load(filename))
	{
		list_.push_back(pix);
	}
}

QPixmap CAdWnd::load_pixmap_from_file(const QString & filename)
{
	QPixmap pix;
	QFile file(filename); 
    auto ret = file.open(QIODevice::ReadOnly);
	pix.loadFromData(file.readAll());
	file.close();
	return pix;
}

void CAdWnd::mousePressEvent(QMouseEvent * event)
{
	emit backToHome();
	QWidget::mousePressEvent(event);
}

void CAdWnd::paintEvent(QPaintEvent * event)
{
	QMutexLocker locker(&mutex_);
	QPainter p(this);
	if (index_ < list_.size())
	{
		p.drawPixmap(rect(), list_[index_]);
	}

    QRect rt(QPoint(1000, 900), QSize(300, 32));
	QFont font;
    // font.setFamily("Adobe Heiti Std R");
	font.setPixelSize(16);
	p.setFont(font);
	p.drawText(rt, version_, Qt::AlignHCenter | Qt::AlignVCenter);
}
